package com.ruhaly.water.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.utils.RegexUtils;
import com.ruhaly.water.R;
import com.ruhaly.water.common.Constant;
import com.ruhaly.water.databinding.ActivityServerSettingBinding;
import com.ruhaly.water.model.Server;
import com.ruhaly.common_lib.base.BaseActivity;
import com.ruhaly.common_lib.utils.JsonUtil;
import com.ruhaly.water.viewmodel.ServerSettingViewModel;


public class ServerSettingActivity extends BaseActivity<ActivityServerSettingBinding> {
    ServerSettingViewModel viewModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_server_setting;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        initVM();
       /*以下控件设置*/
    }

    public void initVM() {
        viewModel = initVM(ServerSettingViewModel.class);
        getB().setViewModel(viewModel);
        viewModel.setServer(JsonUtil.fromJson(Constant.getServerInfo(), Server.class));
    }


    @Override
    public void initTitleFrame() {
        getB().titleFrame.tvTitle.setText("设置");
    }

    public void saveServerInfo(View view) {
        if (TextUtils.isEmpty(viewModel.server.getIp()) || !RegexUtils.isIP(viewModel.server.getIp())) {
            getB().inputLayoutIp.setErrorEnabled(true);
            getB().inputLayoutIp.setError("ip格式不正确");
            getB().etIp.requestFocus();
            return;
        }
        getB().inputLayoutIp.setErrorEnabled(false);
        if (TextUtils.isEmpty(viewModel.server.getPort())) {
            getB().inputLayoutPort.setErrorEnabled(true);
            getB().inputLayoutPort.setError("端口号不能为空");
            getB().etPort.requestFocus();
            return;
        }

        getB().inputLayoutPort.setErrorEnabled(false);

        Constant.saveServerInfo(JsonUtil.toJson(viewModel.server));
        finish();
    }

}
